﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using System.Text;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class UserVendorDA : IUserVendorDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string IS_DEFAULT = "@IS_DEFAULT";
        private string SQL_CHECK_USER_VENDOR_ID_UNIQUE = " SELECT COUNT(1) FROM @_@USER_VENDOR WHERE USER_ID = @USER_ID AND VENDOR_ID = @VENDOR_ID ";
        private string SQL_DELETE_USER_VENDOR = " DELETE FROM @_@USER_VENDOR WHERE USER_ID = @USER_ID ";
        private string SQL_INSERT_USER_VENDOR = " INSERT INTO @_@USER_VENDOR ( USER_ID, VENDOR_ID, IS_DEFAULT, CREATED_BY, CREATED_DATE, UPDATED_BY,UPDATED_DATE) VALUES ( @USER_ID, @VENDOR_ID, @IS_DEFAULT, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE())  ";
        private string SQL_SELECT_ALL_USER_VENDOR = " SELECT  ROWID, USER_ID, VENDOR_ID, IS_DEFAULT, TS, CREATED_BY, CREATED_DATE, UPDATED_BY,UPDATED_DATE  FROM  @_@USER_VENDOR ";
        private string SQL_UPDATE_USER_VENDOR = " UPDATE @_@USER_VENDOR SET IS_DEFAULT = @IS_DEFAULT, UPDATED_BY = @UPDATED_BY ,UPDATED_DATE =GETDATE() WHERE USER_ID = @USER_ID AND VENDOR_ID = @VENDOR_ID  ";
        private string TS = "@TS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string USER_ID = "@USER_ID";
        private string VENDOR_ID = "@VENDOR_ID";

        public bool CheckUserVendorIDUnique(string userID, string VendorID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@VENDOR_ID", VendorID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_USER_VENDOR_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckUserVendorIDUnique(DataBase dataBase, DbTransaction tran, string userID, string VendorID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@VENDOR_ID", VendorID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_USER_VENDOR_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteUserVendor(string userID, string VendorID, string whLoginID)
        {
            string strSql = this.SQL_DELETE_USER_VENDOR.Replace("@_@", whLoginID) + " AND VENDOR_ID = @VENDOR_ID ";
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@VENDOR_ID", VendorID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteUserVendor(DataBase dataBase, DbTransaction tran, string userID, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_USER_VENDOR.Replace("@_@", whLoginID), paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public int DeleteUserVendor(DataBase dataBase, DbTransaction tran, string userID, string VendorID, string whLoginID)
        {
            string strSql = this.SQL_DELETE_USER_VENDOR.Replace("@_@", whLoginID) + " AND VENDOR_ID = @VENDOR_ID ";
            int result = 0;
            try
            {
                SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@VENDOR_ID", VendorID) };
                result += dataBase.ExecuteNonQuery(tran, CommandType.Text, strSql, paras);
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllUserVendor(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_VENDOR.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllUserVendor(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_VENDOR.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public List<UserVendorInfo> GetAuthorizedVendorByUserID(string userID, string whLoginID)
        {
            List<UserVendorInfo> UserVendorList = new List<UserVendorInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT  V.VENDOR_ID,V.COMPANY,UV.IS_DEFAULT FROM {1}Vendor V  INNER JOIN  SYSADM.USER_VENDOR UV ON V.VENDOR_ID = UV.VENDOR_ID WHERE UV.USER_ID='{0}'", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserVendorInfo userVendorInfo = null;
                while (reader.Read())
                {
                    userVendorInfo = new UserVendorInfo(reader["VENDOR_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    UserVendorList.Add(userVendorInfo);
                }
            }
            return UserVendorList;
        }

        public List<UserVendorInfo> GetUnauthorizedVendorByUserID(string userID, string whLoginID)
        {
            List<UserVendorInfo> userVendorList = new List<UserVendorInfo>();
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("   SELECT  V.VENDOR_ID,V.COMPANY, ''AS IS_DEFAULT  FROM {1}Vendor V  WHERE V.VENDOR_ID NOT IN( SELECT VENDOR_ID FROM SYSADM.USER_VENDOR WHERE USER_ID='{0}')", userID, whLoginID);
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                UserVendorInfo userVendorInfo = null;
                while (reader.Read())
                {
                    userVendorInfo = new UserVendorInfo(reader["VENDOR_ID"].ToString(), reader["COMPANY"].ToString(), reader["IS_DEFAULT"].ToString());
                    userVendorList.Add(userVendorInfo);
                }
            }
            return userVendorList;
        }

        public UserVendorInfo GetUserVendorByID(string userID, string vendorID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_VENDOR.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND VENDOR_ID = @VENDOR_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@VENDOR_ID", vendorID) };
            UserVendorInfo userVendorInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    userVendorInfo = new UserVendorInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["VENDOR_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
                }
            }
            return userVendorInfo;
        }

        public UserVendorInfo GetUserVendorByID(DataBase dataBase, DbTransaction tran, string userID, string vendorID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_USER_VENDOR.Replace("@_@", whLoginID) + " WHERE USER_ID = @USER_ID AND VENDOR_ID = @VENDOR_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@USER_ID", userID), new SqlParameter("@VENDOR_ID", vendorID) };
            UserVendorInfo userVendorInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                userVendorInfo = new UserVendorInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["USER_ID"].ToString(), reader["VENDOR_ID"].ToString(), reader["IS_DEFAULT"].ToString(), (byte[]) reader["TS"], reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : new DateTime(), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return userVendorInfo;
        }

        public DataSet GetUserVendorByQueryList(List<string> sqlWhere, UserVendorQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_VENDOR.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!uservendorQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetUserVendorByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, UserVendorQueryEntity uservendorQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_USER_VENDOR.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, uservendorQuery.CurrentPage, uservendorQuery.PageSize, uservendorQuery.SortField, uservendorQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public UserVendorInfo GetVendorByUserID(string userID)
        {
            StringBuilder StrSql = new StringBuilder();
            StrSql.AppendFormat("SELECT VENDOR_ID,IS_DEFAULT FROM SYSADM.USER_VENDOR WHERE IS_DEFAULT='Y' AND USER_ID='{0}'", userID);
            UserVendorInfo userVendorInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, StrSql.ToString()))
            {
                while (reader.Read())
                {
                    userVendorInfo = new UserVendorInfo(reader["VENDOR_ID"].ToString(), "", reader["IS_DEFAULT"].ToString());
                }
            }
            return userVendorInfo;
        }

        public int InsertUserVendor(UserVendorInfo userVendorInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserVendor_Parameters(userVendorInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_VENDOR.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertUserVendor(DataBase dataBase, DbTransaction tran, UserVendorInfo userVendorInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserVendor_Parameters(userVendorInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_USER_VENDOR.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_UserVendor_Parameters(UserVendorInfo userVendorInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.USER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.VENDOR_ID, SqlDbType.VarChar, 20), new SqlParameter(this.IS_DEFAULT, SqlDbType.VarChar, 1), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            paramArray[0].Value = userVendorInfo.UserID;
            paramArray[1].Value = userVendorInfo.VendorID;
            if (!string.IsNullOrEmpty(userVendorInfo.IsDefault))
            {
                paramArray[2].Value = userVendorInfo.IsDefault;
            }
            else
            {
                paramArray[2].Value = DBNull.Value;
            }
            paramArray[3].Value = userVendorInfo.CreatedBy;
            paramArray[4].Value = userVendorInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateUserVendor(UserVendorInfo userVendorInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                SqlParameter[] paras = this.Set_UserVendor_Parameters(userVendorInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_VENDOR.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateUserVendor(DataBase dataBase, DbTransaction tran, UserVendorInfo userVendorInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                SqlParameter[] paras = this.Set_UserVendor_Parameters(userVendorInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_USER_VENDOR.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

